import i18next from 'i18next'
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { create } from 'zustand'

/**
 * 路由信息，用于顶部路由
 */
type Route = {
  path: string
  name: string
}

type State = {
  currentRouteInfos: Route[]
}

type Actions = {
  updateCurrentRouteInfos: (routeInfos: Route[]) => void
}

export const useRouteStore = create<State & Actions>(set => ({
  currentRouteInfos: [],
  updateCurrentRouteInfos: routeInfo => set(() => ({ currentRouteInfos: routeInfo }))
}))

/**
 * 涉及顶部路由信息，在对应页面进行处理，传入路由名称列表，
 * 例如：
 * 知识库 > 详情 > 文件详情 传入对应信息为 [知识库, 详情, 文件详情]
 * 为方便后期扩展中英文和名称都由加载页面时手动传入
 */
export function useRouteStoreHook(pathNameList = []) {
  if (pathNameList.length === 0) return

  const location = useLocation()
  const { updateCurrentRouteInfos } = useRouteStore()

  useEffect(() => {
    const paths = location.pathname.split('/').filter(path => path)
    if (pathNameList.length > paths.length && location.pathname !== '/') {
      console.error('pathNameList 长度超过path配置', pathNameList, paths)
      return
    }

    const routeInfos = []
    let realPaths = [...paths]

    // path数组长度大于pathNameList有效长度时，从数组0下标开始做数据合并
    const diffLen = paths.length - pathNameList.length
    if (diffLen !== 0) {
      let startPath = paths[0]
      for (let i = 1; i < diffLen + 1; i++) {
        startPath = startPath + `/${paths[i]}`
      }
      realPaths = [startPath].concat(paths.slice(diffLen + 1))
    }

    realPaths.reduce((path, currentPath, index) => {
      routeInfos.push({
        path: path + `/${currentPath}`,
        name: pathNameList[index]
      })
      return path + `/${currentPath}`
    }, '')

    console.log('updateCurrentRouteInfos:', routeInfos)
    updateCurrentRouteInfos(routeInfos)
  }, [i18next.language])
}
